package com.letoo.dragon.api.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.letoo.dragon.common.domain.Result;
import com.letoo.dragon.common.domain.ResultCode;
import com.letoo.dragon.common.exception.BusinessException;
import com.letoo.dragon.common.exception.SystemException;

/**
 * spring mvc异常处理器，对controller抛出的异常在此处处理 如果访问的方法有 ResponseBody注解，则认为本次为json请求，返回json字符串，否则返回exception/error错误页面
 * 
 * @author: dengjie
 */
@Component("exceptionResolver")
public class WlHandlerExceptionResolver implements HandlerExceptionResolver {
    /**
     * 日志
     */
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Result result = null;

        if (BusinessException.class.isAssignableFrom(ex.getClass())) {
            BusinessException bex = (BusinessException) ex;
            // 业务异常返回给页面提示
            result = new Result(ResultCode.COMMON_BUSINESS_EXCEPTION, false);
            result.setDescription(ResultCode.COMMON_BUSINESS_EXCEPTION.getDescription());
            result.setResultMap(bex.getResultMap());
            if (bex.getCode() != null) {
                result.setResultCode(bex.getCode());
                result.setDescription(bex.getCode().getDescription());
            }
            log.error("HandlerExceptionResolver catche the Business Exception, " + bex.getMessage(), ex);
        } else if (SystemException.class.isAssignableFrom(ex.getClass())) {
            // 系统异常
            result = new Result(ResultCode.COMMON_SYSTEM_EXCEPTION, false);
            result.setDescription(ResultCode.COMMON_SYSTEM_EXCEPTION.getDescription());
            log.error("HandlerExceptionResolver catche the System Exception, ", ex);
        } else {
            // 系统错误
            result = new Result(ResultCode.COMMON_SYSTEM_ERROR, false);
            result.setDescription(ResultCode.COMMON_SYSTEM_ERROR.getDescription());
            log.error("HandlerExceptionResolver catche the System Error, ", ex);
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(com.alibaba.fastjson.JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("Response write exception", e);
        }

        return new ModelAndView();
    }
}
